<!--
 * @Author: Smthie Smthie@qq.com
 * @Date: 2024-05-28 11:38:08
 * @LastEditors: Smthie Smthie@qq.com
 * @LastEditTime: 2024-05-30 14:57:06
 * @FilePath: \ProtocolTool\src\renderer\src\views\Manual\Socket\SetParam.vue
-->
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { PlusOutlined, FormOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'
import Simplebar from 'simplebar-vue'
import 'simplebar-vue/dist/simplebar.min.css'
import Status from '@/components/TestStatus/index.vue'
import { message } from 'ant-design-vue'
import TextDataBox from '@/components/TextDataBox/index.vue'
import { getTemplateAPI, socketSetParamAPI } from '@/api/Manual'

const loading = ref(false)
const list = ref<any>([])
const status = ref('')
//获取选中设备clientId
const props = defineProps({
  device: {
    type: String,
    default: ''
  }
})

const form = ref<any>({
  ports: [],
  customParams: []
})

// 获取模板数据
const getTemplate = async () => {
  const res = await getTemplateAPI({ testItem: 'set_param' })
  form.value = JSON.parse(res.data.requestData)
  if (!form.value.ports) form.value.ports = []
  if (!form.value.customParams) form.value.customParams = []
}
getTemplate()

/*  tag标签模块--------------------------------------------------------------------------------------*/
const inputRef = ref()
const inputVisible = ref(false)
const inputValue = ref('')
const handleClose = (removedTag) => {
  const tags = form.value.ports?.filter((tag) => tag !== removedTag)
  form.value.ports = tags
}
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value.focus()
  })
}
const handleInputConfirm = () => {
  const inputValue1 = inputValue.value
  const tags = form.value.ports
  if (inputValue1 && tags.indexOf(inputValue1) === -1) {
    tags.push(inputValue1)
  }
  inputVisible.value = false
  inputValue.value = ''
}
// 正则部分
const ipReg =
  /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/
/* 表单校验模块------------------------------------------------------------------------------- */
const formRef = ref()
const rules = {
  parameter: {
    required: true,
    message: '请选择工作参数',
    trigger: 'change'
  },
  ip: {
    validator: (_rule, value) => {
      if (!value) {
        return Promise.resolve()
      } else if (!ipReg.test(value)) {
        return Promise.reject('请输入合法的IP地址')
      } else {
        return Promise.resolve()
      }
    }
  },
  mask: {
    validator: (_rule, value) => {
      if (!value) {
        return Promise.resolve()
      } else if (!ipReg.test(value)) {
        return Promise.reject('请输入合法的子网掩码')
      } else {
        return Promise.resolve()
      }
    }
  },
  gateway: {
    validator: (_rule, value) => {
      if (!value) {
        return Promise.resolve()
      } else if (!ipReg.test(value)) {
        return Promise.reject('请输入合法的网关地址')
      } else {
        return Promise.resolve()
      }
    }
  }
}

const removeItem = (item) => {
  const index = form.value.customParams.indexOf(item)
  if (index !== -1) {
    form.value.customParams.splice(index, 1)
  }
}
const addItem = () => {
  form.value.customParams.push({
    key: '',
    value: ''
  })
}

const handler = () => {
  if (!props.device) {
    message.error('请选择设备')
    return
  }
  form.value.clientId = props.device
  loading.value = true
  status.value = ''
  console.log(form.value)

  socketSetParamAPI(form.value)
    .then((res) => {
      status.value = res.data.resultStatus === 200 ? 'success' : 'fail'
      list.value.unshift({
        id: list.value.length ? list.value[0].id + 1 : 1,
        itemId: res.data.itemId,
        time: Date.now(),
        data: res.data.responseData ? res.data.responseData.replaceAll('\n', '<br/>') : 'null',
        requestData: res.data.requestData ? res.data.requestData.replaceAll('\n', '<br/>') : 'null',
        msg: res.data.result,
        resultStatus: res.data.resultStatus
      })
    })
    .finally(() => {
      loading.value = false
    })
}
</script>
<template>
  <div>
    <div>
      <div class="title">设置工作参数</div>
      <div class="desc">
        通过指令方式设置地球物理专用设备的工作参数，包括网络参数、表述参数、测量参数。
      </div>
    </div>

    <div class="content">
      <div class="left">
        <div class="result">
          <div class="result-title">测试结果</div>
          <div class="result-value">
            <Status :status />
          </div>
        </div>
        <div class="info">
          <a-button class="mb-10" type="primary" block :loading @click="handler">
            <template #icon>
              <FormOutlined />
            </template>
            提交
          </a-button>
          <Simplebar class="data">
            <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
              <a-form-item label="工作参数" name="parameter">
                <a-select
                  ref="select"
                  v-model:value="form.parameter"
                  placeholder="请选择工作参数"
                  style="width: 100%"
                >
                  <a-select-option value="n">网络参数</a-select-option>
                  <a-select-option value="d">表述参数</a-select-option>
                  <a-select-option value="m">测量参数</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item ref="name" label="IP地址" name="ip">
                <a-input v-model:value="form.ip" />
              </a-form-item>
              <a-form-item label="子网掩码" name="mask">
                <a-input v-model:value="form.mask" />
              </a-form-item>
              <a-form-item label="网关" name="gateway">
                <a-input v-model:value="form.gateway" />
              </a-form-item>
              <a-form-item label="端口数量" name="portNum">
                <a-input-number v-model:value="form.portNum" :min="0" style="width: 100%" />
              </a-form-item>
              <a-form-item label="端口数组" name="ports">
                <template v-for="(tag, index) in form.ports" :key="tag">
                  <a-tooltip v-if="tag.length > 20" :title="tag">
                    <a-tag :closable="index !== -1" @close="handleClose(tag)">
                      {{ `${tag.slice(0, 20)}...` }}
                    </a-tag>
                  </a-tooltip>
                  <a-tag v-else :closable="index !== -1" @close="handleClose(tag)">
                    {{ tag }}
                  </a-tag>
                </template>
                <a-input
                  v-if="inputVisible"
                  ref="inputRef"
                  v-model:value="inputValue"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  @blur="handleInputConfirm"
                  @keyup.enter="handleInputConfirm"
                />
                <a-tag v-else style="background: #fff; border-style: dashed" @click="showInput">
                  <plus-outlined />
                  新增端口
                </a-tag>
              </a-form-item>
              <a-form-item label="管理端地址" name="manageIp">
                <a-input v-model:value="form.manageIp" />
              </a-form-item>
              <a-form-item label="管理端端口号" name="managePort">
                <a-input v-model:value="form.managePort" />
              </a-form-item>
              <a-form-item label="SNTP服务器地址" name="sntpIp">
                <a-input v-model:value="form.sntpIp" />
              </a-form-item>
              <a-form-item label="台站ID" name="stationID">
                <a-input v-model:value="form.stationID" />
              </a-form-item>
              <a-form-item label="测项分量代码" name="itemID">
                <a-input v-model:value="form.itemID" />
              </a-form-item>
              <a-form-item label="采样率代码" name="sampleRate">
                <a-input v-model:value="form.sampleRate" />
              </a-form-item>
              <a-form-item label="经度(单位：°)" name="longitude">
                <a-input v-model:value="form.longitude" />
              </a-form-item>
              <a-form-item label="纬度(单位：°)" name="latitude">
                <a-input v-model:value="form.latitude" />
              </a-form-item>
              <a-form-item label="高程(单位: M)" name="elevation">
                <a-input v-model:value="form.elevation" />
              </a-form-item>
              <a-form-item label="通道数" name="accessNum">
                <a-input-number v-model:value="form.accessNum" :min="0" style="width: 100%" />
              </a-form-item>
              <a-form-item label="自定义参数数量" name="customParamAmount">
                <a-input-number
                  v-model:value="form.customParamAmount"
                  :min="0"
                  style="width: 100%"
                />
              </a-form-item>
              <a-form-item label="自定义参数" name="customParams">
                <a-space
                  v-for="item in form.customParams"
                  :key="item.id"
                  class="custom-params"
                  style="display: flex; margin-bottom: 8px"
                  align="center"
                >
                  <a-form-item-rest>
                    <a-input-group compact>
                      <a-input
                        v-model:value="item.key"
                        :status="item.key ? '' : 'error'"
                        style="width: 80px"
                        placeholder="Key"
                      />
                      <a-input
                        v-model:value="item.value"
                        :status="item.value ? '' : 'error'"
                        style="width: 90px"
                        placeholder="Value"
                      />
                    </a-input-group>
                  </a-form-item-rest>
                  <MinusCircleOutlined @click="removeItem(item)" />
                </a-space>
                <a-button type="dashed" block @click="addItem">
                  <PlusOutlined />
                  添加自定义参数
                </a-button>
              </a-form-item>
            </a-form>
          </Simplebar>
        </div>
      </div>

      <div class="right">
        <div class="data-box" style="height: 434px">
          <TextDataBox :list />
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
.title {
  font-weight: 500;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.88);
  line-height: 28px;
}

.desc {
  font-weight: 400;
  font-size: 14px;
  color: #909399;
  line-height: 22px;
  margin: 6px 0 16px;
}

.content {
  display: flex;

  .left {
    width: 200px;

    .result {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10px;
      border-bottom: 1px solid #d9d9d9;

      &-title {
        font-weight: 600;
        font-size: 16px;
      }

      &-value {
        width: 90px;
        height: 28px;
      }
    }

    .data-title {
      line-height: 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        font-size: 16px;
      }

      .time {
        font-size: 12px;
        color: #a8abb2;
      }
    }

    .info {
      background: #ffffff;
      border-radius: 4px;
      width: 200px;
      overflow-x: hidden;
      overflow-y: auto;
      margin-top: 6px;
      background: #ffffff;
      border-radius: 4px;

      .data {
        height: 346px;
        .custom-params {
          :deep(.ant-form-item) {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  .right {
    margin-left: 10px;
    flex: 1;

    ::v-deep(.ant-btn) {
      height: 28px;
      padding: 2px 8px;
    }
  }
}
.ant-btn-primary {
  background-color: rgb(0, 185, 107);
}
.ant-btn-primary:not(:disabled):hover {
  color: #fff;
  background-color: #139937;
}
.ant-btn-default:not(:disabled):hover {
  color: #1a8c35;
  border-color: #139937;
}
</style>
